<template lang="pug">
data-page(
  v-bind="pageParams"
)
  mt-table(
    v-bind="tableProps"
  )
  batchList(v-model="batchListShow" :batchNumber="batchNumber"  @message-to-parent="onSaved")
  templatePreview(v-model="templateShow" :selectRows="selectRow")
  </template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type Action,
  type TableProps,
  useNotify,
  Icon,
  ElMessageBox,
} from "@scmt/common-components";
import { useRequest } from "@scmt/common-hooks";
import { useApi } from "@scmt/core-api";
import type {
  InspectionAgencyEntity,
  InspectionAgencyQueryParams,
} from "@scmt/api-lis-inspection-agency";
import batchList from "./batchList.vue";
import templatePreview from "./templatePreview.vue";

const $api = useApi();
const $notify = useNotify();
const queryPramas = reactive<InspectionAgencyQueryParams>({
  startDate: "",
  endDate: "",
  get _tempDate() {
    return [this.startDate, this.endDate];
  },
  set _tempDate(val) {
    [this.startDate, this.endDate] = val || ["", ""];
  },
  pageNum: 1,
  pageSize: 20,
});
const batchListShow = ref(false);
const templateShow = ref(false);

const batchNumber = ref("");
const selectRow = ref({});

const { request, data, loadingMap } = useRequest({
  tableData: (q: any) => {
    const { _tempDate, ...params } = Object.assign({}, queryPramas, q);
    return $api.lis.inspectionAgency.query(params).then((res) => {
      Object.assign(queryPramas, res.pagination);

      return res;
    });
  },
  save: (model: InspectionAgencyEntity) => {
    return $api.lis.inspectionAgency.save(model).then(() => {
      $notify.success("保存成功");

      getData({
        pageNum: 1,
      });
    });
  },
  listDoctorAsOptions: (val: string) =>
    $api.user.listDoctorAsOptions({ officeId: val }),
  getAll: (q: any) => {
    return $api.lis.specimen.getAll(q);
  },
  cancel: (id: string) => $api.lis.inspectionAgency.cancel(id),
});

onMounted(() => {
  getData();
  request("listDoctorAsOptions");
});

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [
    {
      prop: "batchNumber",
      label: "批次号",
    },
    {
      prop: "_tempDate",
      label: "送检时间",
      as: "date",
      options: {
        type: "daterange",
      },
      span: 6,
    },
  ];
  const headerActions: Action[] = [
    {
      label: "新增批次",
      event: "sampleSubmission",
      type: "primary",
    },
  ];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    actions: headerActions,
    onQuery: getData,
    onAct: onPageActions,
    alignAction: "right",
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: [
      {
        prop: "batchNumber",
        label: "批次号",
        width: 170,
      },
      {
        prop: "state",
        label: "批次状态",
        tooltip: true,
        sortable: true,
        render: ({ row }) => {
          let iconName = "";
          let content = "";
          let color = "";
          switch (row.state) {
            case 1: {
              iconName = "Promotion";
              content = "已送检";
              color = "orange";
              break;
            }
            case 2: {
              iconName = "Memo";
              content = "已签收";
              color = "green";
              break;
            }
          }
          return h(
            "div",
            {
              style: {
                display: "flex",
                alignItems: "center",
              },
            },
            [
              h(Icon, {
                name: iconName,
                style: {
                  color: color,
                },
              }),
              h(
                "span",
                {
                  style: {
                    marginLeft: "var(--mt-margin-small)",
                  },
                },
                content
              ),
            ]
          );
        },
      },
      {
        prop: "source",
        label: "业务来源",
        tooltip: true,
        sortable: true,
      },
      {
        prop: "outward",
        label: "送检类型",
        tooltip: true,
        sortable: true,
        render: ({ cellValue }: { cellValue: 0 | 1 }) =>
          cellValue === 1 ? "外送" : "自检",
      },
      {
        prop: "specimenType",
        label: "标本类型",
        tooltip: true,
      },
      {
        prop: "numberPeople",
        label: "样品数量",
        tooltip: true,
      },
      {
        prop: "sendInspectionId",
        label: "送检人",
        tooltip: true,
        render: ({ row }) => {
          const patientType = data.listDoctorAsOptions ?? [];
          let resText = row.sendInspectionId;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.sendInspectionId
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "generationTime",
        label: "送检时间",
        tooltip: true,
        sortable: true,
      },
      {
        label: "操作",
        fixed: "right",
        actions: [
          {
            label: "送检明细",
            event: "detailed",
            type: "primary",
          },
          {
            label: "取消送检",
            event: "cancel",
            type: "danger",
          },
          {
            label: "打印送检单",
            event: "print",
            type: "primary",
          },
        ],
      },
    ],
    onAct: onPageActions,
    onPaginate: getData,
    highlightCurrentRow: true,
  };
  return tableProps;
});

const onPageActions = (action: IAction, model?: InspectionAgencyEntity) => {
  switch (action.event) {
    case "detailed":
    case "sampleSubmission":
      batchNumber.value = model?.batchNumber ? model.batchNumber : "";
      batchListShow.value = true;
      break;
    case "print":
      templateShow.value = true;
      selectRow.value = $api.lis.inspectionAgency.$$createEntity(model);
      break;
    case "cancel":
      ElMessageBox.confirm("取消送检将删除当前记录，是否取消？", {
        title: "提示",
        type: "warning",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;

            await request("cancel", {
              params: model!.id,
              onSuccess: () => {
                $notify.success("取消成功");

                getData({
                  pageNum: 1,
                });
              },
            });

            done();
            instance.confirmButtonLoading = false;
          } else {
            done();
          }
        },
      });
      break;
  }
};

function getData(q?: any) {
  request("tableData", q);
}

const onSaved = () => {
  getData({
    pageNum: 1,
  });
};
</script>

<style lang="less" scoped></style>
